<?php
/**
 * ModulesParam data mapper
 * 
 * Implements the Data Mapper design pattern
 * 
 * @version $Id: ModulesParamMapper.php 73 2010-04-25 00:30:44Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Default_Model_DbTable_ModulesParam
 * @package default
 * @subpackage Model
 */
class Default_Model_ModulesParamMapper
{

    protected $_dbTable = null;

    /**
     * Specify Zend_Db_Table instance to use for data operations
     * 
     * @param Zend_Db_Table_Abstract $$dbTable
     * @return Default_Model_ModulesParamMapper
     */
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
        	$dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
        	throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    /**
     * Get registered Zend_Db_Table instance
     * 
     * Lazy loads Default_Model_ModulesParam if no instance registered
     * 
     * @return Zend_Db_Table_Abstract
     */
    public function getDbTable()
    {
        if (null === $this->_dbTable) {
        $this->setDbTable('Default_Model_DbTable_ModulesParam');
        }
        return $this->_dbTable;
    }

    /**
     * Find a modules_param entry by a key
     * 
     * @param int $id
     * @param Default_Model_ModulesParam $modules_param
     * @return void
     */
    public function save($modules_param)
    {
        $data = array(
        	'resource_id' => $modules_param->getResource_id(),
        	'param' => $modules_param->getParam(),
        	'value' => $modules_param->getValue(),
        );
        if (null === ($sn = $modules_param->getSn()
        )) {
        	unset($data['sn']);
        	$this->getDbTable()->insert($data);
        } else {
        	$this->getDbTable()->update($data, array('sn = ?' => $sn));
        }
    }

    /**
     * Save a modules_param entry
     * 
     * @param Default_Model_ModulesParam $modules_param
     * @return void
     */
    public function find($id, $modules_param)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
        	return;
        }
        $row = $result->current();
        $modules_param->setSn($row->sn)
        	->setResource_id($row->resource_id)
        	->setParam($row->param)
        	->setValue($row->value)
        	;
    }

    /**
     * Fetch all modules_param entries
     * 
     * @return array
     */
    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
        	$entry = new Default_Model_ModulesParam();
        	$entry->setSn($row->sn)
        	->setResource_id($row->resource_id)
        	->setParam($row->param)
        	->setValue($row->value)
        	;
        	$entries[] = $entry;
        }
        return $entries;
    }


}
